package com.java.cloud.pay.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.druid.pool.DruidDataSource;
import com.java.cloud.pay.entity.Payment;
import com.java.cloud.pay.handler.CustomerHandler;
import com.java.cloud.pay.service.PaymentService;
import com.java.common.utils.PageUtils;
import com.java.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;



/**
 * 支付表
 *
 * @author jl
 * @since 2020-03-09 23:01:59
 */
@RestController
@RequestMapping("pay/payment")
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    /**
     * 分页查询
     * 当前页码page、每页显示记录数limit
     */
    @RequestMapping("/list")
    public R<PageUtils> list(@RequestParam Map<String, Object> params){
        PageUtils page = paymentService.queryPage(params);

	    return R.ok(page);
    }


    /**
     * 根据主键查询
     */
    @RequestMapping("/info/{id}")
    public R<Payment> info(@PathVariable("id") Long id){
		Payment payment = paymentService.getById(id);
	    return R.ok(payment);
    }

    /**
     * 新增
     */
    @RequestMapping("/save")
    public R save(@RequestBody Payment payment){
		paymentService.save(payment);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody Payment payment){
		paymentService.updateById(payment);

	    return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		paymentService.removeByIds(Arrays.asList(ids));

	    return R.ok();
    }

	@GetMapping("/sentinelA")
	public String sentinelA() {
    	return "sentinelA";
	}

	@GetMapping("/sentinelB")
	public String sentinelB() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		log.info(Thread.currentThread().getName()+"...sentinelB");
		return "sentinelB";
	}

	@GetMapping("/testHotKey")
	@SentinelResource(value = "testHotKey",blockHandler = "testHotKey_block")
	public String testHotKey(@RequestParam(value = "p1",required = false)String p1,
	                         @RequestParam(value = "p2",required = false)String p2) {
    	return "...testHotKey";
	}

	public String testHotKey_block(String p1, String p2, BlockException e) {
		return "热点流控...testHotKey_block";
	}

	@GetMapping("/rateLimit/customerHandler")
	@SentinelResource(value = "customerHandler",blockHandlerClass = CustomerHandler.class,blockHandler = "handlerException2",
			fallback = "fallbackMethod")
	public R customerHandler() {
    	return R.ok();
	}

	public R fallbackMethod() {
    	return R.error("系统异常,请稍后重试!");
	}


}
